﻿(function (global) {
    var days = 24 * 60 * 60,
        hours = 60 * 60,
        minutes = 60;
    function countdown() { };

    countdown.prototype = {
        init: function (option) {
            var def = {
                ts: (new Date()).getTime() + 10 * 24 * 60 * 60 * 1000,
                //format: {day:true,hour:true,minute:true,second:true},
                callback: function () { },
                endCallback: function () { }
            };
            for (var key in def) {
                if (!!option[key]) {
                    def[key] = option[key];
                }
            }
            var d, m, s;
            //left = left < 0 ? 0 : left;

            function _format(digit) {
                return String(Math.floor(digit / 10) % 10) + String(digit % 10);
            }

            (function () {
                var left = Math.floor((def.ts - (new Date())) / 1000);
                        
                if (left < 0) {
                    def.endCallback();
                    return;
                }

                // Number of days left
                d = Math.floor(left / days);
                left -= d * days;

                // Number of hours left
                h = Math.floor(left / hours);
                left -= h * hours;

                // Number of minutes left
                m = Math.floor(left / minutes);
                left -= m * minutes;

                // Number of seconds left
                s = left;

                // number of days(99 is the biggest),hours,minutes,seconds
                //console.log(s);
                def.callback({ d: _format(d), h: _format(h), m: _format(m), s: _format(s) });
                setTimeout(arguments.callee, 1000);
            })();
        }
    };

    global.countdown = new countdown();
})(window);
(function ($) {
    var countTime = $("#count-time"),
                hours = countTime.children(".hours"),
                minutes = countTime.children(".minutes"),
                seconds = countTime.children(".seconds");
    countdown.init({
        ts: (new Date()).getTime() + 5 * 1000,
        callback: function (data) {
            hours.text(data.h);
            minutes.text(data.m);
            seconds.text(data.s);
        }
    });

})(jQuery);